package com.example.futureai.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.example.futureai.dto.ChatDto;
import com.example.futureai.dto.DocVtsDto;
import com.example.futureai.dto.News;
import com.example.futureai.eum.ChatTYpe;
import com.example.futureai.po.ChatSessionRecord;
import com.example.futureai.po.UserSession;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: ChatUtil
 * @Description:
 * @Author: YourName
 * @Date: 2025/4/7
 */

public class ChatUtil {

    public static final String CHAT_TYPE_AI = "ai";
    public static final String CHAT_TYPE_USER = "user";
    // 主分组方法
    public static Map<String, List<UserSession>> groupByCreateTime(List<UserSession> list) {
        if (list == null || list.isEmpty()) {
            return new LinkedHashMap<>();
        }

        // 获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();
        LocalDate today = now.toLocalDate();
        LocalDate yesterday = today.minusDays(1);

        // 按时间分组
        Map<String, List<UserSession>> grouped = list.stream()
                .collect(Collectors.groupingBy(obj -> {
                    LocalDateTime createTime = obj.getCreateTime();
                    LocalDate createDate = createTime.toLocalDate();
                    if (createDate.isEqual(today)) {
                        return "今天";
                    } else if (createDate.isEqual(yesterday)) {
                        return "昨天";
                    } else if (createDate.isAfter(today.minusDays(7))) {
                        return "7天内";
                    } else if (createDate.isAfter(today.minusDays(30))) {
                        return "30天内";
                    } else {
                        // 更早的按年月分组
                        return createTime.format(DateTimeFormatter.ofPattern("yyyy年M月"));
                    }
                }));
        // 定义分组顺序
        List<String> groupOrder = Arrays.asList("今天", "昨天", "7天内", "30天内");
        // 按指定顺序排序分组
        Map<String, List<UserSession>> sortedMap = new LinkedHashMap<>();

        // 先添加预定义的分组
        groupOrder.forEach(group -> {
            if (grouped.containsKey(group)) {
                sortedMap.put(group, grouped.get(group));
            }
        });
        // 然后添加按年月分组的项（按时间倒序）
        grouped.entrySet().stream()
                .filter(entry -> !groupOrder.contains(entry.getKey()))
                .sorted((e1, e2) -> {
                    // 按年月降序排列
                    return e2.getKey().compareTo(e1.getKey());
                })
                .forEachOrdered(entry -> sortedMap.put(entry.getKey(), entry.getValue()));

        return sortedMap;
    }

    // 将UserSession转换为ChatSessionRecord
    public static List<ChatDto> toChatSessionRecord(List<ChatSessionRecord> list) {
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }
        List<ChatDto> chatDtoList = new ArrayList<>();
        list.stream().forEach(shatSessionRecord -> {
            //AI记录
            String chatType = shatSessionRecord.getChatType();
            if(StrUtil.isBlank(chatType)){
                chatType = ChatTYpe.TEXT.getType();
            }
            ChatDto aiChatDto = new ChatDto();
            aiChatDto.setType(CHAT_TYPE_AI);
            aiChatDto.setContent(shatSessionRecord.getContent());
            aiChatDto.setMsgId(shatSessionRecord.getId()+"_"+CHAT_TYPE_AI);
            aiChatDto.setChatType(chatType);
            if(StrUtil.isNotBlank(shatSessionRecord.getFiles())){
                List<DocVtsDto> file = JSONUtil.toList(shatSessionRecord.getFiles(), DocVtsDto.class);
                aiChatDto.setMatchtoFiles(file);
            }
            //用户记录
            ChatDto userChatDto = new ChatDto();
            userChatDto.setType(CHAT_TYPE_USER);
            userChatDto.setContent(shatSessionRecord.getQuestion());
            userChatDto.setMsgId(shatSessionRecord.getId()+"_"+CHAT_TYPE_USER);
            chatDtoList.add(userChatDto);
            chatDtoList.add(aiChatDto);
        });
        return chatDtoList;
    }


    public static List<News> grabBaiduHotNews(){
        String url = "https://top.baidu.com/board?tab=realtime&sa=fyb_realtime_31065";
        List<News> list = new ArrayList<>();
        try {
            Document doc = Jsoup.connect(url).get();
            //标题
            Elements titles = doc.select(".c-single-text-ellipsis");
            //图片
            Elements imgs = doc.select(".category-wrap_iQLoo .index_1Ew5p").next("img");
            //内容
            Elements contents = doc.select(".hot-desc_1m_jR.large_nSuFU");
            //推荐图
            Elements urls = doc.select(".category-wrap_iQLoo a.img-wrapper_29V76");
            //热搜指数
            Elements levels = doc.select(".hot-index_1Bl1a");
            for (int i = 0; i < levels.size(); i++) {
                News o = new News();
                o.setTitle(titles.get(i).text().trim());
                o.setImg(imgs.get(i).attr("src"));
                o.setContent(contents.get(i).text().replaceAll("查看更多>", "").trim());
                o.setUrl(urls.get(i).attr("href"));
                o.setLevel(levels.get(i).text().trim());
                list.add(o);
            }
            System.out.println("百度热点数据抓取"+JSONUtil.toJsonStr(list));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
